import { useLocation } from "react-router-dom";
// import Plyr from "plyr";
/// hack way to import plyr.css
// import "plyr/dist/plyr.css";
import dayjs from "dayjs";
import _ from "lodash";
import { useEffect, useRef, useState } from "react";
import { v4 as uuidV4 } from "uuid";
import NavBar from "../components/NavBar";
import Comment from "../components/Video/Comment";
import Note from "../components/Video/Note";
import VideoInfo from "../components/Video/VideoInfo";
import VideoPlayer from "../components/Video/VideoPlayer";
import "./Video.css";
import { get } from "../utilities";

export default function Video() {
  /// state.videoId is used to get video
  const { state } = useLocation();
  const [videoURLs, setVideoURLs] = useState({
    videoURL: "",
    posterURL: "",
    captionURL: "",
  });
  const [videoTitle, setVideoTitle] = useState("");
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(1);
  const [stared, setStared] = useState(false);
  const [starCount, setStarCount] = useState(2);
  const [isComponentVisible, setIsComponentVisible] = useState(true);
  const [showPopup, setShowPopup] = useState(false);
  const [videoTimeStamp, setVideoTimeStamp] = useState(0);

  // should get video metadata here
  useEffect(() => {
    get("http://110.42.231.196:8000/video/metadata", {
      videoId: state.videoId,
    }).then((videoInfo) => {
      setVideoTitle(videoInfo.title);
      setLikeCount(videoInfo.thumbsUpNum);
    });

    setVideoURLs({
      videoURL: "http://110.42.231.196:8000/video?videoId=" + state.videoId,
      posterURL:
        "http://110.42.231.196:8000/video/poster?videoId=" + state.videoId,
      captionURL:
        "http://110.42.231.196:8000/video/caption?videoId=" + state.videoId,
    });
  }, [state]);

  const handleLike = () => {
    setLiked(!liked);
    setLikeCount(likeCount + (liked ? -1 : 1));
  };

  const handleComment = () => {
    setIsComponentVisible(!isComponentVisible);
  };
  const handleStar = () => {
    setStared(!stared);
    setStarCount(starCount + (stared ? -1 : 1));
  };
  const handleMouseEnter = () => {
    setShowPopup(true);
  };

  const handleMouseLeave = () => {
    setShowPopup(false);
  };

  const handleShareButtonClick = () => {
    setShowPopup(!showPopup);
  };

  const handleSaveToLocal = async () => {
    const response = await fetch(videoURLs.videoURL);
    const blob = await response.blob();
    const urlObject = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.style.display = "none";
    a.href = urlObject;
    a.download = videoTitle + ".mp4";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(urlObject);
    setShowPopup(false);
  };

  const downloadVideo = () => {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", videoURLs.videoURL, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      var urlCreator = window.URL || window.webkitURL;
      var videoUrl = urlCreator.createObjectURL(this.response);
      var tag = document.createElement("a");
      tag.href = videoUrl;
      tag.download = videoTitle + ".mp4";
      document.body.appendChild(tag);
      tag.click();
      document.body.removeChild(tag);
    };
    xhr.onerror = (err) => {
      alert(err + ": Failed to download the video");
    };
    xhr.send();
    setShowPopup(false);
  };

  const handleCopyLink = () => {
    navigator.clipboard.writeText(videoURLs.videoURL).then(() => {
      alert("视频链接已复制");
      setShowPopup(false);
    });
  };

  function useGetList() {
    const [commentList, setCommentList] = useState([]);
    const [commentCount, setCommentCount] = useState(0);
    const [user, setUser] = useState({});
    const [avatar, setAvatar] = useState("");
    useEffect(() => {
      async function getList() {
        // const res = await axios.get("http://127.0.0.1:3004/list");
        /// fake one
        const res = {
          data: [
            {
              rpid: 1,
              user: {
                uid: "1",
                avatar: "https://p.qqan.com/up/2020-9/16010876389657332.jpg",
                uname: "LL",
              },
              content: "哎哟，不错哦",
              ctime: "2024年5月18日",
              like: 5,
            },
            {
              rpid: 2,
              user: {
                uid: "2",
                avatar:
                  "https://th.bing.com/th/id/OIP.qkn-u2DXXEJ6L2KxAWHZ9wAAAA?rs=1&pid=ImgDetMain",
                uname: "WW",
              },
              content: "可以",
              ctime: "2024年5月20日",
              like: 3,
            },
          ],
        };
        setCommentList(res.data);
        setCommentCount(res.data.length);
        setUser(res.data[0].user);
        setAvatar(res.data[0].user.avatar);
      }
      getList();
    }, []);
    return {
      commentList,
      setCommentList,
      commentCount,
      setCommentCount,
      user,
      setUser,
      avatar,
    };
  }

  const {
    commentList,
    setCommentList,
    commentCount,
    setCommentCount,
    user,
    avatar,
  } = useGetList();
  const [type, setType] = useState("hot");
  const tabs = [
    { type: "hot", text: "最热" },
    { type: "time", text: "最新" },
  ];

  const handleTabChange = (type) => {
    console.log(type);
    setType(type);
    if (type === "hot") {
      setCommentList(_.orderBy(commentList, "like", "desc"));
    } else {
      setCommentList(_.orderBy(commentList, "ctime", "desc"));
    }
  };

  const [content, setContent] = useState("");
  const inputRef = useRef(null);

  const handlPublish = (e) => {
    e.preventDefault();
    if (content.trim()) {
      setCommentCount(commentCount + 1);
      setCommentList([
        ...commentList,
        {
          rpid: uuidV4(),
          user: {
            uid: user.uid,
            avatar: user.avatar,
            uname: user.uname,
          },
          content: content,
          ctime: dayjs(new Date()).format("YYYY年M月D日"),
          like: 0,
        },
      ]);
      setContent("");
      inputRef.current.focus();
    } else {
      alert("评论内容不能为空");
    }
  };

  const [replyliked, setReplyLiked] = useState(false);
  const [replyLikeId, setReplyLikeId] = useState(0);
  const handleReplyLike = (id) => {
    setReplyLiked((prevState) => !prevState);
    setReplyLikeId(id);
    const newList = commentList.map((item) => {
      if (item.rpid === id) {
        item.like = replyliked ? item.like - 1 : item.like + 1;
      }
      return item;
    });
    setCommentList(newList);
  };

  const [replyTreaded, setReplyTreaded] = useState(false);
  const [replyTreadId, setReplyTreadId] = useState(0);
  const handleReplyTread = (id) => {
    setReplyTreaded((prevState) => !prevState);
    setReplyTreadId(id);
    const newList = commentList.map((item) => {
      if (item.rpid === id) {
        if (replyTreaded === true) {
          item.like = item.like + 1;
        } else {
          item.like = item.like - 1;
        }
      }
      return item;
    });
    setCommentList(newList);
  };

  const [replyId, setReplyId] = useState(0);
  const [isReplyComponentVisible, setIsReplyComponentVisible] = useState(false);
  const handleReply = (id) => {
    setReplyId(id);
    setIsReplyComponentVisible(!isReplyComponentVisible);
  };

  const [showMore, setShowMore] = useState(false);
  const [replyMoreId, setReplyMoreId] = useState(0);

  const handleMore = (id) => {
    setReplyMoreId(id);
    setShowMore(!showMore);
  };

  const handleReplyDelete = (id) => {
    setCommentCount(commentCount - 1);
    console.log(id);
    setCommentList(commentList.filter((item) => item.rpid !== id));
  };

  const handleReplyReport = (id) => {};

  const handleMoreMouseLeave = () => {
    setShowMore(false);
    setReplyMoreId(null);
  };

  return (
    <>
      <NavBar />
      <div className="u-flex">
        <div className="Video-container" data-testid="Video">
          {videoURLs.videoURL.length > 0 ? (
            <VideoPlayer
              posterURL={videoURLs.posterURL}
              videoURL={videoURLs.videoURL}
              captionURL={videoURLs.captionURL}
              timeStamp={videoTimeStamp}
              setTimeStamp={setVideoTimeStamp}
            />
          ) : (
            "Loading"
          )}
          {videoTitle.length > 0 ? (
            <VideoInfo
              title={videoTitle}
              liked={liked}
              likeCount={likeCount}
              handleLike={handleLike}
              commentCount={commentCount}
              handleComment={handleComment}
              stared={stared}
              starCount={starCount}
              handleStar={handleStar}
              downloadURL={videoURLs.videoURL}
              handleMouseEnter={handleMouseEnter}
              handleMouseLeave={handleMouseLeave}
              handleShareButtonClick={handleShareButtonClick}
              showPopup={showPopup}
              handleSaveToLocal={downloadVideo}
              handleCopyLink={handleCopyLink}
            />
          ) : (
            "Loading"
          )}
          {videoTitle.length > 0
            ? isComponentVisible && (
                <Comment
                  liked={replyliked}
                  replyLikeId={replyLikeId}
                  treaded={replyTreaded}
                  replyTreadId={replyTreadId}
                  content={content}
                  setContent={setContent}
                  inputRef={inputRef}
                  commentCount={commentCount}
                  commentlist={commentList}
                  handleTabChange={handleTabChange}
                  handlPublish={handlPublish}
                  type={type}
                  tabs={tabs}
                  user={user}
                  avatar={avatar}
                  handleReplyLike={handleReplyLike}
                  handleReplyTread={handleReplyTread}
                  replyId={replyId}
                  isComponentVisible={isReplyComponentVisible}
                  handleReply={handleReply}
                  handleMore={handleMore}
                  showMore={showMore}
                  replyMoreId={replyMoreId}
                  handleReplyDelete={handleReplyDelete}
                  handleReplyReport={handleReplyReport}
                  handleMouseLeave={handleMoreMouseLeave}
                />
              )
            : "Loading"}
        </div>
        <Note videoTimeStamp={videoTimeStamp} />
      </div>
    </>
  );
}
